/*
 * @Author: 谢小康 2170673706@qq.com
 * @Date: 2023-12-08 14:05:46
 * @LastEditors: 谢小康 2170673706@qq.com
 * @LastEditTime: 2024-02-06 14:28:50
 * @FilePath: \My-bolg\server\controller\user.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
const {
    login,
    getUserByID,
    updatauser,
    updatapaword,
    findoneUserbyname,
    addUser,
    getsitedata,
    getalluser,
    getuserNum,
    deleteuser,
    changeRole
} = require("../serve/users.js")
const jwt = require("../util/jwt.js")
const { getQiniuToken } = require("../util/qiniuUpload.js")
const Response = require("../util/respanse.js")
const getconfig = require("../config/getconfig.js")
const userslist = require("../data/user.js")
const routerlist = require("../data/router.js")
const { randomUUID } = require("crypto")
const IP2Region = require('ip2region').default
const { getClientIp } = require("../util/utils.js")
let { deleteList, deleteimg } = require("../util/qiniuUpload.js");
/* 用户登录 */
const tologin = async (req, res) => {
    try {
        // 获取用户名和密码
        const { username, password } = req.body;
        const { code, users } = await login(username, password);
        if (code == 1) {
            let { Users_role, Users_address, Users_password, Users_name, id, Users_corver } = users
            if (Users_password == password) {
                loginseccess(res, id, Users_name, Users_role, Users_address, Users_corver)
            } else {
                Response.errorresponse(res, {
                    code: 400,
                    msg: "密码错误"
                });
            }
        } else {
            Response.errorresponse(res, {
                code: 400,
                msg: "用户名或密码错误",
            })
        }
    } catch (error) {
        console.log(error);
        Response.errorresponse(res, {
            code: 400,
            msg: "用户名或密码错误",
        })
    }
}
/* 判断用户是否存在 */
const isuser = async (req, res) => {
    try {
        const { username } = req.body;
        if (!username) {
            Response.errorresponse(res, {
                code: 400,
                msg: "不能为空",
            })
        }
        if (req.headers?.authorization) {
            /* 如果refasion_token有效的话 */
            let token = req.headers.authorization.split(" ")[1];
            if (token) {
                const { id, Users_name, Users_role, Users_address, Users_corver } = jwt.verify(token);
                if (username == Users_name) {
                    Response.successresponse(res, {
                        code: 200,
                        message: "用户名可用",
                    })
                }else{
                    const { code } = await login(username);
                    if (code) {
                        Response.errorresponse(res, {
                            code: 400,
                            msg: "用户名重复",
                        })
                    } else {
                        Response.successresponse(res, {
                            code: 200,
                            message: "用户名可用",
                        })
                    }
                }
            } else {
                Response.errorresponse(res, {
                    code: 401,
                    msg: "未登录",
                })
            }
        }else{
            Response.errorresponse(res, {
                code: 401,
                msg: "未登录",
            })
        }
    } catch (error) {
        console.log(error);
        Response.errorresponse(res, {
            code: 400,
            msg: "出错了",
        })
    }
}
/*  */
const canuser = async (req, res) => {
    try {
        const { username } = req.body;
        const { code } = await login(username);
        if (code) {
            Response.errorresponse(res, {
                code: 400,
                msg: "用户名重复",
            })
        } else {
            Response.successresponse(res, {
                code: 200,
                message: "用户名可用",
            })
        }
    } catch (error) {
        console.log(error);
        Response.errorresponse(res, {
            code: 400,
            msg: "出错了",
        })
    }
}
/* 判断是否登录 */
const adjustLogin = async (req, res) => {
    try {
        if (req.headers?.authorization) {
            /* 如果refasion_token有效的话 */
            let token = req.headers.authorization.split(" ")[1];
            if (token) {
                jwt.verify(token);
                Response.successresponse(res, {
                    code: 200,
                    message: "ok",
                    data: {
                        isLogin: true,
                    },
                })
            } else {
                Response.errorresponse(res, {
                    code: 401,
                    message: "未登录",
                })
            }
        }
    } catch (error) {
        Response.errorresponse(res, {
            code: 401,
            message: "出错了",
        })
    }
}
/* 刷新token */
const refreshtoken = async (req, res) => {
    try {
        if (req.headers?.authorization) {
            try {
                /* 如果refasion_token有效的话 */
                let token = req.headers.authorization.split(" ")[1];

                const { id, Users_name, Users_role, Users_address, Users_corver } = jwt.verify(token);
                /* 创建新的refreshToken 和 accessToken */
                loginseccess(res, id, Users_name, Users_role, Users_address, Users_corver, false)
            } catch (err) {
                switch (err.name) {
                    case "TokenExpiredError":
                        console.error("token已过期", err);
                        return Response.errorresponse(res, {
                            code: 401,
                            msg: "token已过期 TokenExpiredError",
                            err
                        });
                    case "JsonWebTokenError":
                        console.error("无效的token", err);
                        return Response.errorresponse(res, {
                            code: 401,
                            msg: "无效token JsonWebTokenError",
                            err
                        });
                }
            }
        } else {

        }
    } catch (error) {
    }
}
/* 登录函数 */
const loginseccess = (res, id, Users_name, Users_role, Users_address, Users_corver, fleg = true) => {
    /* fleg表示调用这个方法的是刷新token还是登录 true表示登录 false表示刷新token*/
    if (fleg) {
        var access_token = jwt.sign({ id, Users_name, Users_role, Users_corver }, "1h")
        var refresh_token = jwt.sign({ id, Users_name, Users_role, Users_address, Users_corver }, "7d")
    } else {
        let acc = randomUUID()
        var access_token = jwt.sign({ id, Users_name, Users_role, Users_corver, acc }, "1h")
        var refresh_token = jwt.sign({ id, Users_name, Users_role, Users_address, Users_corver, acc }, "7d")
    }
    const headers = {
        access_token: "Bearer" + " " + access_token,
        refresh_token: "Bearer" + " " + refresh_token,
    }
    let message = "登录成功";
    if (!fleg) {
        message = "刷新token成功";
    }
    Response.successresponse(res, {
        code: 200,
        message: message,
        data: {
            id,
            Users_name,
            Users_corver,
        },
    }, headers)
}
/* 通过用户ID查询 当前用户id的路由 */
const getAuthByuserid = async (req, res) => {
    try {
        if (req.headers?.authorization) {
            /* 根据角色id查询角色权限 */
            /* 如果refasion_token有效的话 */
            let token = req.headers.authorization.split(" ")[1];
            if (token) {
                let jwtres = jwt.verify(token);
                let ress = await getUserByID(jwtres.id);
                if (ress.code) {
                    /* 用户存在 */
                    /* 先查询user_role 在去userlist里面比对用户权利, 筛选出路由*/
                    let authRouterInfo = []
                    const { Users_role } = ress.users;
                    let auth_user = userslist.filter((item) => item.id == Users_role)[0]
                    auth_user.auth.map(rid => {
                        routerlist.map(router => {
                            if (router.id == rid) {
                                authRouterInfo.push(router);
                            }
                        })
                    })
                    Response.successresponse(res, {
                        code: 200,
                        message: "查询成功",
                        data: {
                            authRouterInfo,
                            authname: auth_user.name
                        }
                    })
                } else {
                    /* 用户不存在 */
                    Response.errorresponse(res, {
                        code: 400,
                        message: "没有用户信息",
                    })
                }
            } else {
                Response.errorresponse(res, {
                    code: 401,
                    message: "未登录",
                })
            }
        } else {
            /* 参数错误*/
            Response.errorresponse(res, {
                code: 400,
                msg: "token错误",
            })
        }
    } catch (error) {
        console.error(error);
        Response.errorresponse(res, {
            code: 400,
            message: "返回失败",
            err: error
        })
    }
}

/* 获取七牛云的token,发返回给前端上传文件 */
const getqiniutoken = async (req, res) => {
    try {
        let data = getQiniuToken()
        console.log(data.msg);
        if (data.code) {
            Response.successresponse(res, {
                code: 200,
                message: data.msg,
                data: {
                    uploadToken: data.uploadToken,
                    upLimitTime: data.UPLIMITTIME,
                }
            })
        } else {
            Response.successresponse(res, {
                code: 400,
                message: data.msg,
                data: {}
            })
        }
    } catch (error) {
        Response.successresponse(res, {
            code: 200,
            message: "查询成功",
            data: {
            }
        })
    }
}
/* 判断是否是高级管理员 */
const isSuperAdmin = async (req, res, next) => {
    try {
        if (req.headers?.authorization) {
            /* 根据角色id查询角色权限 */
            /* 如果refasion_token有效的话 */
            let token = req.headers.authorization.split(" ")[1];
            if (token) {
                let jwtres = jwt.verify(token);
                let ress = await getUserByID(jwtres.id);
                if (ress.code) {
                    /* 用户存在 */
                    if (ress.users.Users_role !== 1) {
                        Response.errorresponse(res, {
                            code: 402,
                            msg: "非管理员",
                        })
                    } else {
                        next()
                    }
                } else {
                    /* 用户不存在 */
                    Response.errorresponse(res, {
                        code: 400,
                        msg: "用户不存在",
                    })
                }
            } else {
                Response.errorresponse(res, {
                    code: 401,
                    message: "未登录",
                })
            }
        } else {
            /* 参数错误*/
            Response.errorresponse(res, {
                code: 400,
                msg: "token错误",
            })
        }
    } catch (error) {
        console.log(error);
        /* 用户不存在 */
        Response.errorresponse(res, {
            code: 500,
            msg: "出错了",
            err: error
        })
    }
}
/* 获取用户 */
const getuser = async (req, res) => {
    let token = req.headers.authorization;
    if (token) {
        if (token.startsWith("Bearer ")) {
            token = token.split(" ")[1];
        }
        let jwtres = jwt.verify(token);
        if (jwtres) {
            let ress = await getUserByID(jwtres.id);
            if (ress.code) {
                /* 用户存在 */
                Response.successresponse(res, {
                    code: 200,
                    data: ress.users,
                    message: "获取用户成功"
                })
            } else {
                Response.errorresponse(res, {
                    code: 400,
                    msg: "用户不存在",
                })
            }

        }
    }
}
const updateuser = async (req, res) => {
    try {
        let { name, avatar } = req.body;
        let token = req.headers.authorization;
        if (token) {
            if (token.startsWith("Bearer ")) {
                token = token.split(" ")[1];
            }
            let jwtres = jwt.verify(token);
            if (jwtres) {
                let ress = await getUserByID(jwtres.id);
                if (ress.code) {
                    /* 用户存在 */
                    let resss = await updatauser({ name, avatar, id: jwtres.id });
                    if (resss.code) {
                        let resse = await getUserByID(jwtres.id);
                        Response.successresponse(res, {
                            code: 200,
                            data: resse.users,
                            message: "修改用户成功"
                        })
                    } else {
                        Response.errorresponse(res, {
                            code: 400,
                            msg: "修改失败",
                        })
                    }
                } else {
                    Response.errorresponse(res, {
                        code: 400,
                        msg: "用户不存在",
                    })
                }
            }
        }
    } catch (error) {
        console.log(error);
        Response.errorresponse(res, {
            code: 500,
            msg: "出错了",
        })
    }
}
/* 修改密码 */
const changepassword = async (req, res) => {
    try {
        let { newpassword, oldpassword } = req.body;
        if (!newpassword || !oldpassword) {
            Response.errorresponse(res, {
                code: 400,
                msg: "参数错误",
            })
        }
        let token = req.headers.authorization;
        if (token) {
            if (token.startsWith("Bearer")) {
                token = token.split(" ")[1];
            }
            let jwtres = jwt.verify(token);
            if (jwtres) {
                let ress = await getUserByID(jwtres.id);
                if (ress.code) {
                    /* 用户存在 */
                    let resss = await updatapaword(newpassword, oldpassword, jwtres.id);
                    if (resss.code) {
                        Response.successresponse(res, {
                            code: 200,
                            message: "修改成功"
                        })
                    } else {
                        Response.errorresponse(res, {
                            code: 400,
                            msg: "修改失败,密码错误",
                        })
                    }
                } else {
                    Response.errorresponse(res, {
                        code: 400,
                        msg: "用户不存在",
                    })
                }

            }
        }
    } catch (error) {
        console.log(error);
        Response.errorresponse(res, {
            code: 500,
            msg: "出错了",
        })
    }
}
/* 注册 */
const registerusr = async (req, res) => {
    try {
        let { username, password } = req.body;
        let ip = getClientIp(req);
        // 创建一个IP2Region实例
        const query = new IP2Region();
        const ipAddress = query.search(ip);
        if (!username || !password) {
            Response.errorresponse(res, {
                code: 400,
                msg: "参数错误",
            })
            return
        } else {
            let ress = await findoneUserbyname(username);
            if (ress.code) {
                Response.errorresponse(res, {
                    code: 400,
                    msg: "用户名已存在",
                })
            } else {
                let rees = await addUser(username, password, ipAddress.city);
                if (rees.code) {
                    Response.successresponse(res, {
                        code: 200,
                        message: "注册成功"
                    })
                } else {
                    Response.errorresponse(res, {
                        code: 400,
                        msg: "注册失败",
                    })
                }
            }
        }

    } catch (error) {
        console.log(error);
        Response.errorresponse(res, {
            code: 500,
            msg: "出错了",
        })
    }
}
/* 获取首页信息 */
const getdata = async (req, res) => {
    try {
        let ress = await getsitedata()
        Response.successresponse(res, {
            code: 200,
            message: "成功",
            data: ress.data,
        })
    } catch (error) {
        console.log(error);
        Response.errorresponse(res, {
            code: 500,
            msg: "出错了",
        })
    }
}
/* 分页获取用户 */
const getallusers = async (req, res) => {
    try {
        let { page, pageSize, keyword } = req.query
        let ress = await getalluser(page, pageSize, keyword)
        if (ress.code) {
            Response.successresponse(res, {
                code: 200,
                message: "成功",
                data: ress.data,
            })
        } else {
            Response.successresponse(res, {
                code: 400,
                data: "",
                message: "暂无数据",
            })
        }
    } catch (error) {
        console.log(error);
        Response.errorresponse(res, {
            code: 500,
            msg: "出错了",
        })
    }
}
/* 获取用户个数 */
const getusernum = async (req, res) => {
    try {
        let ress = await getuserNum()
        Response.successresponse(res, {
            code: 200,
            message: "成功",
            data: ress.data,
        })
    } catch (error) {
        console.log(error);
        Response.errorresponse(res, {
            code: 500,
            msg: "出错了",
        })
    }
}
const deleteusers = async (req, res) => {
    try {
        let { deleteidlist } = req.body
        let ress = await deleteuser(deleteidlist)
        if (ress.code) {
            Response.successresponse(res, {
                code: 200,
                message: "成功",
            })
        } else {
            Response.errorresponse(res, {
                code: 400,
                msg: "失败",
            })
        }
    } catch (error) {
        console.log(error);
        Response.errorresponse(res, {
            code: 500,
            msg: "出错了",
        })
    }
}
const deleteuserscorver = async (req, res) => {
    try {
        let { corverlist } = req.body
        let newlist = corverlist.filter(item => {
            return item !== "2024011919245858472.jpg"
        })
        console.log(newlist);
        if (newlist.length > 0) {
            let fleg = new Promise((resolve, reject) => {
                deleteList(newlist, async function (err, respBody, respInfo) {
                    if (err) {
                        console.log(err);
                        reject(true)
                    } else {
                        if (parseInt(respInfo.statusCode / 100) == 2) {
                            respBody.forEach(function (item) {
                                if (item.code == 200) {
                                    console.log(item.code + "\tsuccess");
                                }
                            })
                        }
                    }

                })
            })
        } else {
            fleg = false
        }
        if (!fleg) {
            Response.successresponse(res, {
                code: 200,
                message: "成功",
            })
        } else {
            Response.errorresponse(res, {
                code: 400,
                msg: "失败",
            })
        }
    } catch (error) {
        console.log(error);
        Response.errorresponse(res, {
            code: 500,
            msg: "出错了",
        })
    }
}
const tochangerole = async (req, res) => {
    try {
        let { userid, role } = req.body
        let ress = await getUserByID(userid);
        if (ress.code) {
            if (ress.users.Users_role != role) {
                let resp = await changeRole(userid, role);
                if (resp.code) {
                    Response.successresponse(res, {
                        code: 200,
                        message: "成功",
                    })
                } else {
                    Response.errorresponse(res, {
                        code: 400,
                        msg: "失败",
                    })
                }
            } else {
                Response.errorresponse(res, {
                    code: 400,
                    msg: "角色未改变",
                })
            }
        }
    } catch (error) {
        console.log(error);
        Response.errorresponse(res, {
            code: 500,
            msg: "出错了",
        })
    }
}
module.exports = {
    tologin,
    adjustLogin,
    refreshtoken,
    getAuthByuserid,
    getqiniutoken,
    isSuperAdmin,
    getuser,
    updateuser,
    changepassword,
    registerusr,
    getdata,
    getallusers,
    getusernum,
    deleteusers,
    deleteuserscorver,
    tochangerole,
    isuser,
    canuser
}